﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using BookStore.Solution.Entities;
using BookStore.Solution.BLL;
using BookStore.Solution.Utilities;

namespace BookStore.Solution.Presentation
{
    public partial class frmBill : DevComponents.DotNetBar.OfficeForm
    {
        BillManager billManager=new BillManager();
        string name="";
        BillDetailManager billdetail=new BillDetailManager();
 
        public List<BillDetail> listBillDetail = new List<BillDetail>();
        public List<BillDetail> list = new List<BillDetail>();
        public Bill newBill { get; set; }
        DataTable MyBillDetailtable = null;
        string Status = "";
        long uniprice=0;
        public string result { get; set; }
        PromotionManager promotion = new PromotionManager();
        ProductManager products = new ProductManager();
        public frmBill()
        {
            InitializeComponent();
            this.Status = "insert";
        }
        public frmBill(Bill bill)
         {
            InitializeComponent();
            newBill = bill;
            this.Status = "update";
        }
        public frmBill(Bill bill, string status)
        {
            InitializeComponent();
            this.newBill = bill;
            this.Status = "view";
        }
        private DataTable CreateTable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ProductID", Type.GetType("System.String"));
            dt.Columns.Add("ProductName", Type.GetType("System.String"));
            dt.Columns.Add("Quantity", Type.GetType("System.Int32"));
            dt.Columns.Add("UnitPrice", Type.GetType("System.Int64"));
            return dt;
        }
        private void FrmBill_Load(object sender, EventArgs e)
        {
            cbbPromotion.DataSource = promotion.GetAll();
            cbbPromotion.DisplayMember = "PromotionName";
            cbbPromotion.ValueMember = "PromotionID";
            if (Status.CompareTo("update") == 0 || Status.CompareTo("view") == 0)
            {
                txtBillID.Text = newBill.BillID.ToString();
                txtEmployID.Text = newBill.EmployeeID;
                dtpDay.Value = newBill.Date;
                if (newBill.PromotionID != "")
                {
                    cbbPromotion.Text = promotion.SearchbyID(newBill.PromotionID).Rows[0].ItemArray[1].ToString();
                    ckbPromotion.Checked = true;
                }
                else
                    ckbPromotion.Checked = false;
                LoadDataGridview(newBill);
                listBillDetail = GetTable();
                if (Status.CompareTo("update") == 0)
                {
                    ReturnQuantity();
                    list = GetTable();
                }
                if (ckbPromotion.Checked == true)
                {
                    DataTable a = promotion.SearchbyID(cbbPromotion.SelectedValue.ToString());
                    DataRow dr = a.Rows[0];
                    int b = int.Parse(dr["Discount"].ToString());
                    txtMoney.Text = (uniprice * (100 - b) / 100).ToString();
                }
                else
                    txtMoney.Text = uniprice.ToString();
            }
            else
            {
                MyBillDetailtable = CreateTable();
                txtEmployID.Text = AccountManager.CurrentAccount.EmployeeID;
                txtMoney.Text = "0";
            }
        }
        private void ReturnQuantity()
        {
            foreach (var item in listBillDetail)
            {
                products.UpdateProduct(item,1);
            }
        }
        private List<BillDetail> GetTable()
        {
            List<BillDetail> list = new List<BillDetail>();
            for (int i = 0; i < dtgvListProduct.RowCount; i++)
            {
                BillDetail b = new BillDetail();
                b.BillID = newBill.BillID;
                b.ProductID = dtgvListProduct.Rows[i].Cells[0].Value.ToString();
                b.Quantity = int.Parse(dtgvListProduct.Rows[i].Cells[2].Value.ToString());
                b.UnitPrice = long.Parse(dtgvListProduct.Rows[i].Cells[3].Value.ToString());
                b.Status = "Đang tồn tại";
                list.Add(b);
            }
            return list;
        }
        private void  LoadDataGridview(Bill bill)
        {
        
            MyBillDetailtable = billdetail.SearchID(bill.BillID);
            LoadData(MyBillDetailtable);
        }
        private void btnThem_Click(object sender, EventArgs e)
        {
            bool check = true;
            frmBillDetail frmdetail = new frmBillDetail();
            frmdetail.ShowDialog();
            if (this.Status.CompareTo("insert") == 0)
            {
                if (frmdetail.newdetail != null)
                {
                    for (int i = 0; i < dtgvListProduct.RowCount; i++)
                    {
                        if (dtgvListProduct.Rows[i].Cells[0].Value.ToString().Equals(frmdetail.newdetail.ProductID))
                        {
                            dtgvListProduct.Rows[i].Cells[2].Value = int.Parse(dtgvListProduct.Rows[i].Cells[2].Value.ToString()) + frmdetail.newdetail.Quantity;
                            check = false;
                        }
                    }
                    if (check)
                    {
                        name = frmdetail.productName;
                        InsertDatagridview(frmdetail.newdetail);
                    }
                    if (ckbPromotion.Checked == true)
                    {
                        DataTable a = promotion.SearchbyID(cbbPromotion.SelectedValue.ToString());
                        DataRow dr = a.Rows[0];
                        int b = int.Parse(dr["Discount"].ToString());
                        txtMoney.Text = (int.Parse(txtMoney.Text) + frmdetail.newdetail.Quantity * frmdetail.newdetail.UnitPrice * (100 - b) / 100).ToString();
                    }
                    else
                        txtMoney.Text = (int.Parse(txtMoney.Text) + frmdetail.newdetail.Quantity * frmdetail.newdetail.UnitPrice).ToString();
                }
            }
            if (this.Status.CompareTo("update") == 0)
            {
                if (frmdetail.newdetail != null)
                {
                    for (int i = 0; i < dtgvListProduct.RowCount; i++)
                    {
                        if (dtgvListProduct.Rows[i].Cells[0].Value.ToString().Equals(frmdetail.newdetail.ProductID))
                        {
                            dtgvListProduct.Rows[i].Cells[2].Value = int.Parse(dtgvListProduct.Rows[i].Cells[2].Value.ToString()) + frmdetail.newdetail.Quantity;
                            for (int j = 0; j < listBillDetail.Count; j++)
                            {

                                if (listBillDetail[j].ProductID.CompareTo(frmdetail.newdetail.ProductID) == 0)
                                {
                                    listBillDetail[j].Quantity += frmdetail.newdetail.Quantity;
                                    check = false;
                                    break;
                                }
                            }
                        }
                    }
                    if (check)
                    {
                        name = frmdetail.productName;
                        InsertDatagridview(frmdetail.newdetail);
                        listBillDetail.Add(frmdetail.newdetail);
                    }
                    if (ckbPromotion.Checked == true)
                    {
                        DataTable a = promotion.SearchbyID(cbbPromotion.SelectedValue.ToString());
                        DataRow dr = a.Rows[0];
                        int b = int.Parse(dr["Discount"].ToString());
                        txtMoney.Text = (int.Parse(txtMoney.Text) + frmdetail.newdetail.Quantity * frmdetail.newdetail.UnitPrice * (100 - b) / 100).ToString();
                    }
                    else
                        txtMoney.Text = (int.Parse(txtMoney.Text) + frmdetail.newdetail.Quantity * frmdetail.newdetail.UnitPrice).ToString();
                }
            }
        }
        private void InsertDatagridview(BillDetail Bdetail)
        {
            dtgvListProduct.Rows.Add(Bdetail.ProductID, name, Bdetail.Quantity, Bdetail.UnitPrice);
        }
        private void LoadData(DataTable table)
        {
            foreach (DataRow row in table.Rows)
            {
                dtgvListProduct.Rows.Add(row["ProductID"], name, row["Quantity"], row["UnitPrice"]);
            }
            if (this.Status.CompareTo("update") == 0 || this.Status.CompareTo("view") == 0)
            {
                for (int i = 0; i < dtgvListProduct.RowCount; i++)
                {
                    uniprice += int.Parse(dtgvListProduct.Rows[i].Cells[2].Value.ToString()) * long.Parse(dtgvListProduct.Rows[i].Cells[3].Value.ToString());
                    string a = dtgvListProduct.Rows[i].Cells[0].Value.ToString();
                    dtgvListProduct.Rows[i].Cells["ProductName"].Value = billManager.GetNameProduct(a);
                }
                
            }
        }
        private void btnOK_Click(object sender, EventArgs e)
        {
            Product p;
            if (checkValidation())
            {
                if (this.Status.CompareTo("insert") == 0)
                {
                   
                        Bill b = GetBill();
                        int billid = billManager.Insert(b);
                        for (int i = 0; i < dtgvListProduct.RowCount; i++)
                        {

                            BillDetail billdetails = new BillDetail();
                            billdetails.ProductID = dtgvListProduct.Rows[i].Cells[0].Value.ToString();
                            billdetails.BillID = billid;
                            billdetails.Quantity = int.Parse(dtgvListProduct.Rows[i].Cells[2].Value.ToString());
                            billdetails.UnitPrice = long.Parse(dtgvListProduct.Rows[i].Cells[3].Value.ToString());
                            billdetails.Status = "Đang tồn tại";
                            p = products.SearchByID(billdetails.ProductID);
                            p.Quatity = p.Quatity - billdetails.Quantity;
                            products.UpdateProduct(p);
                            billdetail.InsertBillDetail(billdetails);
                        }
                        newBill = b;                   
                }
                if (this.Status.CompareTo("update") == 0)
                {
                    foreach (var item in listBillDetail)
                    {
                        if (item.Status.CompareTo("Chưa tồn tại") == 0)
                        {
                            item.BillID = newBill.BillID;
                            item.Status = "Đang tồn tại";
                            billdetail.InsertBillDetail(item);
                        }
                        else
                            billdetail.UpdateStatus(item);
                        products.UpdateProduct(item, -1);

                    }
                    newBill.Date = dtpDay.Value;
                    if (ckbPromotion.Checked == true)
                    {
                        newBill.PromotionID = cbbPromotion.SelectedValue.ToString();
                    }
                    else
                        newBill.PromotionID = null;
                    result = billManager.UpdateStatus(newBill);

                    if (result.CompareTo("Cập nhật thành công")==0)
                    {
                        MessageBox.Show("Cập nhập hóa đơn thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        newBill = newBill;

                    }
                }
                this.Status = "close";
                Close();
            }
        }
        private bool checkValidation()
        {
            if (dtgvListProduct.RowCount==0)
            {
                MessageBox.Show("Hóa đơn không có sản phẩm nào", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            return true;
        }
        private Bill GetBill()
        {
            Bill b = new Bill();
            b.EmployeeID = AccountManager.CurrentAccount.EmployeeID;
            b.Date = dtpDay.Value ;
            b.Status = "Đang tồn tại";
            if (ckbPromotion.Checked == true)
            {
                b.PromotionID = cbbPromotion.SelectedValue.ToString();
            }
            else
                b.PromotionID = null;
            return b;
        }
        private void btnXoa_Click(object sender, EventArgs e)
        {
            if (dtgvListProduct.SelectedRows.Count > 0)
            {
                 DialogResult result  = MessageBox.Show("Bạn muốn xóa chi tiết hóa đơn ?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                 if (result == DialogResult.Yes)
                 {
                     if (this.Status.CompareTo("insert") == 0)// sao lai insert// nếu là thêm hóa đơn
                     {
                         if (ckbPromotion.Checked == true)//????
                         {
                             DataTable a = promotion.SearchbyID(cbbPromotion.SelectedValue.ToString());
                             DataRow dr = a.Rows[0];
                             int b = int.Parse(dr["Discount"].ToString());
                             long ab = int.Parse(dtgvListProduct.SelectedRows[0].Cells[2].Value.ToString()) * long.Parse(dtgvListProduct.SelectedRows[0].Cells[3].Value.ToString());
                             txtMoney.Text = (long.Parse(txtMoney.Text) - ab * (100 - b) / 100).ToString();
                         }
                         else
                             txtMoney.Text = (long.Parse(txtMoney.Text) - (int.Parse(dtgvListProduct.Rows[dtgvListProduct.CurrentRow.Index].Cells[2].Value.ToString()) * long.Parse(dtgvListProduct.Rows[dtgvListProduct.CurrentRow.Index].Cells[3].Value.ToString()))).ToString();
                         dtgvListProduct.Rows.RemoveAt(dtgvListProduct.CurrentRow.Index);
                     }
                     if (this.Status.CompareTo("update") == 0)
                     {
                         foreach (var item in listBillDetail)
                         {
                             if (dtgvListProduct.SelectedRows[0].Cells[0].Value.ToString().CompareTo(item.ProductID) == 0)
                             {
                                 if (ckbPromotion.Checked == true)
                                 {
                                     DataTable a = promotion.SearchbyID(cbbPromotion.SelectedValue.ToString());
                                     DataRow dr = a.Rows[0];
                                     int b = int.Parse(dr["Discount"].ToString());
                                     long ab = int.Parse(dtgvListProduct.SelectedRows[0].Cells[2].Value.ToString()) * long.Parse(dtgvListProduct.SelectedRows[0].Cells[3].Value.ToString());
                                     txtMoney.Text = (long.Parse(txtMoney.Text) - ab * (100 - b) / 100).ToString();
                                 }
                                 else
                                     txtMoney.Text = (long.Parse(txtMoney.Text) - (int.Parse(dtgvListProduct.Rows[dtgvListProduct.CurrentRow.Index].Cells[2].Value.ToString()) * long.Parse(dtgvListProduct.Rows[dtgvListProduct.CurrentRow.Index].Cells[3].Value.ToString()))).ToString();
                                 item.Status = "Đã xóa";
                                 break;
                             }
                         }
                         dtgvListProduct.Rows.RemoveAt(dtgvListProduct.CurrentRow.Index);
                     }
                 }
            }
            else
                MessageBox.Show("Bạn chưa chọn hóa đơn chi tiết nào để xóa", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        private List<string> GetBillDetail()
        {
            List<string> bdt = new List<string>();
            if (this.Status.Equals("insert"))
            {
                bdt.Add("");
            }
            else
            {
                bdt.Add(newBill.BillID.ToString());
            }
            bdt.Add(dtgvListProduct.SelectedRows[0].Cells[0].Value.ToString());
            bdt.Add(dtgvListProduct.SelectedRows[0].Cells[1].Value.ToString());
            bdt.Add(dtgvListProduct.SelectedRows[0].Cells[2].Value.ToString());
            bdt.Add(dtgvListProduct.SelectedRows[0].Cells[3].Value.ToString());
            return bdt;
        }
        private void btnCapNhat_Click(object sender, EventArgs e)
        {
            if (dtgvListProduct.SelectedRows.Count > 0)
            {
                List<string> bdt = GetBillDetail();
                frmBillDetail frmdetail = new frmBillDetail(bdt);
                frmdetail.ShowDialog();
                if (frmdetail.newdetail != null)
                {
                    for (int i = 0; i < dtgvListProduct.RowCount; i++)
                    {
                        if (dtgvListProduct.Rows[i].Cells[0].Value.ToString().Equals(frmdetail.newdetail.ProductID))
                        {
                            if (ckbPromotion.Checked == true)
                            {
                                DataTable a = promotion.SearchbyID(cbbPromotion.SelectedValue.ToString());
                                DataRow dr = a.Rows[0];
                                int b = int.Parse(dr["Discount"].ToString());
                                txtMoney.Text = (long.Parse(txtMoney.Text) + (frmdetail.newdetail.Quantity * frmdetail.newdetail.UnitPrice) * (100 - b) / 100 - (int.Parse(dtgvListProduct.Rows[dtgvListProduct.CurrentRow.Index].Cells[2].Value.ToString()) * long.Parse(dtgvListProduct.Rows[dtgvListProduct.CurrentRow.Index].Cells[3].Value.ToString()) * (100 - b) / 100)).ToString();
                            }
                            else
                                txtMoney.Text = (long.Parse(txtMoney.Text) + (frmdetail.newdetail.Quantity * frmdetail.newdetail.UnitPrice) - (int.Parse(dtgvListProduct.Rows[dtgvListProduct.CurrentRow.Index].Cells[2].Value.ToString()) * long.Parse(dtgvListProduct.Rows[dtgvListProduct.CurrentRow.Index].Cells[3].Value.ToString()))).ToString();
                            dtgvListProduct.Rows[i].Cells[2].Value = frmdetail.newdetail.Quantity;
                        }
                    }
                    if (this.Status.CompareTo("update") == 0)
                    {
                        for (int i = 0; i < listBillDetail.Count; i++)
                        {
                            if (listBillDetail[i].ProductID.CompareTo(frmdetail.newdetail.ProductID) == 0)
                            {
                                listBillDetail[i].Quantity = frmdetail.newdetail.Quantity;
                            }
                        }
                    }

                }
            }
            else
                MessageBox.Show("Bạn chưa chọn hóa đơn chi tiết cần sửa", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {

            DialogResult dl = MessageBox.Show("Bạn muốn hủy các thao tác trên hóa đơn", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
            if (dl == DialogResult.Yes)
            {
                foreach (var item in list)
                {
                    products.UpdateProduct(item, -1);
                }
                this.Status = "close";
                Close();
            }
        }

        private void frmBill_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (this.Status.CompareTo("close") != 0)
            {
                DialogResult dl = MessageBox.Show("Bạn muốn hủy các thao tác trên hóa đơn", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                if (dl == DialogResult.Yes)
                {
                    foreach (var item in list)
                    {
                        products.UpdateProduct(item, -1);
                    }
                    Close();
                }
            }
        }

        private void ckbPromotion_CheckedChanged(object sender, EventArgs e)
        {
            long money = 0;
            for (int i = 0; i < dtgvListProduct.RowCount; i++)
            {
                money = money + int.Parse(dtgvListProduct.Rows[i].Cells[2].Value.ToString()) * long.Parse(dtgvListProduct.Rows[i].Cells[3].Value.ToString());
            }
            if (ckbPromotion.Checked == true)
            {

                DataTable a = promotion.SearchbyID(cbbPromotion.SelectedValue.ToString());
                DataRow dr = a.Rows[0];
                int b = int.Parse(dr["Discount"].ToString());
                txtMoney.Text = (money * (100 - b) / 100).ToString();
            }
            else
                txtMoney.Text = money.ToString();
                
        }

        private void cbbPromotion_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ckbPromotion.Checked == true)
            {
                long money = 0;
                for (int i = 0; i < dtgvListProduct.RowCount; i++)
                {
                    money = money + int.Parse(dtgvListProduct.Rows[i].Cells[2].Value.ToString()) * long.Parse(dtgvListProduct.Rows[i].Cells[3].Value.ToString());
                }
                DataTable a = promotion.SearchbyID(cbbPromotion.SelectedValue.ToString());
                DataRow dr = a.Rows[0];
                int b = int.Parse(dr["Discount"].ToString());
                txtMoney.Text = (money * (100 - b) / 100).ToString();
            }
        }
    }
}